<template>
  <el-card class="box-card">
    <template #header>
      <div class="card-header">
        <span>我的审批</span>
      </div>
    </template>

    <div class="table-data" v-loading="loading">
      <el-table :data="fundData" stripe borderresizable highlight-hover-row show-overflow keep-source scrollbar-always-on>
        <el-table-column v-for="(tableItem, tableIndex) in fundTableColumns" :key="tableIndex" :prop="tableItem.field"
          :label="tableItem.label" :min-width="tableItem.minWidth" :formatter="tableItem.formatter"
          show-overflow-tooltip></el-table-column>
        <el-table-column fixed="right" field="opera" label="操作" min-width="120">
          <template #default="{ row }">
            <el-button type="warning" link @click="fundDetail(row)">查看</el-button>
            <el-button type="success" link @click="fundApprove(row)"
              v-if="row.check_show == 1 && ( row.approvalId ? row.approvalId.split(',').includes(authStore.userInfo.uid) : '')">审核</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="table-page">
        <el-pagination background layout="prev, pager, next" :total="dataTotal" :page-size="pageSize"
          :current-page="currentPage" @current-change="currentChange" />
      </div>
    </div>

    <fill-approval-dialog v-model:visible="dialogVisible" @approvalChange="approvalChange" />
  </el-card>
</template>

<script>
export default { name: 'backendLearnfund' }
</script>

<script setup>
import { ref, reactive, onMounted, watch, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import fillApprovalDialog from "@/components/backend/fillApproval.vue"
import { http } from '@/utils/http/index';
import { dateFormatter } from "@/utils/backend.js"
import { useAuthStore } from '@/stores/modules/auth.js'
import { ContentTypeEnum } from '@/enums/httpEnum';
import { format } from '@/plugins/moment.js'
/* 路由 */
const router = useRouter()
const route = useRoute()

onMounted(() => {
  onSubmit()
})

/* 分页 */
const dataTotal = ref(0)
const pageSize = ref(20)
const currentPage = ref(1)

if (router.currentRoute.value.query.currentPage) {
  currentPage.value = Number(router.currentRoute.value.query.currentPage)
}

/* 切换页码方法 */
const currentChange = (val) => {
  currentPage.value = val
  onSubmit()
}

/* 表格数据加载动画 */
const loading = ref(false)

/* 表格数据 */
const fundData = ref([])

const achievementFormFormatter = (row, column, cellValue) => {
  return cellValue ? cellValue == '1' ? '专著或论文' : '研究报告' : ''
}

const nodeStatusFormatter = (row, column, cellValue) => {
  let obj = [
    { label: '未到本审核节点', value: 0 },
    { label: '待审核', value: 1 },
    { label: '本节点审核通过', value: 2 },
    { label: '本节点审核未通过', value: -1 },
  ]
  let find = obj.find((item) => item.value == cellValue)
  return find ? find.label : ""
}

const approvaldateFormatter = (row, column, cellValue) => {
  return format(cellValue) != '0001-01-01' ? format(cellValue) : ''
}

/* 表格字段 */
const fundTableColumns = reactive([
  { field: "docName", label: "申报标题", minWidth: "200" },
  { field: "flowName", label: "当前审批节点", minWidth: "200" },
  { field: "approvalName", label: "审批人", minWidth: "200" },
  { field: "createdDate", label: "申报日期", minWidth: "120", formatter: dateFormatter },
  { field: "approvalDate", label: "审批日期", minWidth: "140", formatter: approvaldateFormatter },
  { field: "check_show", label: "审核状态", minWidth: "140", formatter: nodeStatusFormatter },
])

watch(() => router.currentRoute.value.path, () => {
  onSubmit()
})

const flowType = computed(() => {
  const current = route.path.replace(/\/backend/g, '')
  // 社科基金
  if (current == '/learn-fund-approval') return 0
  // 宣讲集体
  if (current == '/publicize-collectiveness-approval') return 1
  // 先进个人
  if (current == '/publicize-personal-approval') return 2
  // 优秀理论宣讲报告
  if (current == '/publicize-report-approval') return 3
  // 优秀理论宣讲微视频
  if (current == '/publicize-video-approval') return 4
  return ''
})

/* 点击搜索 */
const onSubmit = (type) => {
  loading.value = true

  let params = {
    pageIndex: currentPage.value,
    pageSize: pageSize.value,
    dfi: {
      Logic: 0,
      Filters: [{
        Field: 'flowType',
        Operator: 8,
        Value: flowType.value
      }]
    }
  }

  const url = flowType.value === 0 ? '/DeclarationM/GetSocialScienceFundInfoList_MyCheck' : '/PreachM/GetPreachFillingInfoList_MyCheck'
  http.$POST(url, params).then(res => {
    loading.value = false
    if (res.isError) return
    fundData.value = res.result.dataLst
    dataTotal.value = res.result.countAll
  }).catch(() => {
    loading.value = false
    ElMessage.warning("查询失败，请重试")
  })
}

/* 查看详情 */
const fundDetail = (row) => {
  let url;
  // 社科基金
  if (flowType.value == 0) url = '/backend/learn-fund/detail'
  // 宣讲集体
  if (flowType.value == 1) url = '/backend/publicize-collectiveness/detail'
  // 先进个人
  if (flowType.value == 2) url = '/backend/publicize-personal/detail'
  // 优秀理论宣讲报告
  if (flowType.value == 3) url = '/backend/publicize-report/detail'
  // 优秀理论宣讲微视频
  if (flowType.value == 4) url = '/backend/publicize-video/detail'
  let { href } = router.resolve({
    path: url,
    query: { id: row.docId, flowId: row.flowId }
  })
  window.open(href, "_blank")
}

/* 审核弹窗 */
const dialogVisible = ref(false)

/* 当前列数据 */
const currentColumn = ref({})

/* 点击审核 */
const fundApprove = (row) => {
  dialogVisible.value = true
  currentColumn.value = row
}

const authStore = useAuthStore()
/* 提交审核 */
const approvalChange = (approvalForm) => {
  /* return */
  const params = {
    FlowId: currentColumn.value.flowId,
    FlowNo: currentColumn.value.flowNo,
    FlowName: currentColumn.value.flowName,
    FlowType: flowType.value,
    NodeId: currentColumn.value.id,
    NodeName: currentColumn.value.nodeName,
    ApprovalId: authStore.userInfo.uid,
    ApprovalName: authStore.userInfo.name,
    ApprovalStatus: approvalForm.approval == 1 ? 1 : 0,
    ApprovalComments: approvalForm.des,
    ApprovalDate: format(new Date()),
  }

  changeCheckStatus(params)
}

/* 更改状态值 */
const changeCheckStatus = (params) => {
  const isSocial = route.path.replace(/\/backend/g, '') == '/learn-fund-approval'
  const url = isSocial ? '/DeclarationM/SocialScienceFundInfo_Check' : '/PreachM/PreachFillingInfo_Check'
  // 路径参数
  const urlParams = Object.entries(params)
    .reduce((pre, [key, value]) => `${pre}${key}=${value}&`, '?')
    + `authToken=${authStore.auth_token}`

  http.$POST(url + urlParams, params).then(res => {
    if (res.isError) {
      ElMessage.warning('操作失败');
    } else {
      ElMessage.success('操作成功');
      onSubmit()
    }
  }).catch(() => {
    ElMessage.warning('操作失败');
  })
}
</script>

<style lang='scss' scoped>
@import "@/assets/styles/backendElement.scss";
</style>